package com.hiray.demos.etc

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.appcompat.app.AppCompatActivity
import android.text.Editable
import android.text.Spannable
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.util.Log
import com.hiray.demos.R
import com.hiray.demos.etc.room.AppDataBase
import com.hiray.demos.etc.room.Article
import com.hiray.demos.etc.room.ArticleDao
import com.hiray.demos.widget.CursorEditText
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_large_text_room.*

class LargeTextRoomActivity : AppCompatActivity() {

    private val TAG = "LargeTextRoomActivity"
    lateinit var dispoable: Disposable
    lateinit var disposable1: Disposable
    var id: Long = 0
    lateinit var articleDao: ArticleDao
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_large_text_room)
        setSupportActionBar(toolbar)
        init()
    }

    @SuppressLint("CheckResult")
    private fun init() {
        loadFont()
        articleDao = AppDataBase.getInstance(applicationContext).articleDao()
        disposable1 = Observable
                .create<List<Article>> {
                    var list = articleDao.getArticle()
                    it.onNext(list)
                    it.onComplete()
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it != null && !it.isEmpty()) {
                        val article = it[0]
                        editor_title.setText(article.title)
                        toolbar.subtitle = "字数：${article.content.length}"
                        val spannableString = SpannableString(article.content)
//                        editor.setTextColor(ContextCompat.getColor(this@LargeTextRoomActivity, R.color.color_unhilight))
                        colorSpan = ForegroundColorSpan(ContextCompat.getColor(this@LargeTextRoomActivity, R.color.color_unhilight))
                        spannableString.setSpan(colorSpan, 0, article.content.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                        editor.setText(spannableString)
                        id = article.id
                    } else {
                        id = articleDao.createArticle(Article(0, editor_title.text.toString(), editor.text.toString()))
                    }
                    bindTextChangeWithDatabase()
                }, {

                }, {

                })

    }

    var lastLine = -1

    private fun bindTextChangeWithDatabase() {

        editor.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                toolbar.subtitle = "字数：${s?.length}"
                val selectionStart = editor.selectionStart
                val selectionEnd = editor.selectionEnd
                Log.i(TAG, "onTextChanged: $s  $selectionStart  $selectionEnd")

                processSingleLineHighLight(selectionStart, selectionEnd, true)
                articleDao.updateArticle(Article(id, editor_title.text.toString(), editor.text.toString()))
            }

        })


        editor.selectionChangeListener = object : CursorEditText.OnSelectionChangeListener {
            private var currSelStart = 0
            override fun onSelectionChanged(selStart: Int, selEnd: Int) {
                Log.i(TAG, "onSelectionChanged: ")
                processSingleLineHighLight(selStart, selEnd, false)
            }
        }
    }

    private lateinit var colorSpan: ForegroundColorSpan
    private fun processSingleLineHighLight(selStart: Int, selEnd: Int, forceUpdate: Boolean) {
        if (selStart == 0 && selEnd == 0)
            return
        val line = editor.layout.getLineForOffset(selStart)
        val lineTextStart = editor.layout.getLineStart(line)
        val lineTextEnd = editor.layout.getLineEnd(line)

        if (lastLine == line && forceUpdate.not())
            return
        else lastLine = line
        editor.setTextColor(ContextCompat.getColor(this, R.color.color_unhilight))
        val text = editor.text
        //去除剪切板文字的样式
        val spans = text!!.getSpans(0, editor.text!!.length, ForegroundColorSpan::class.java)
        spans.forEach {
            text.removeSpan(it)
        }
        colorSpan = ForegroundColorSpan(Color.BLACK)
        text.setSpan(colorSpan, lineTextStart, lineTextEnd, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        editor.postInvalidate()

    }

    private fun loadFont() {
        editor.typeface = Typeface.createFromAsset(assets, "NotoSansSC-Regular.woff2.otf")
    }

    override fun onDestroy() {
        super.onDestroy()
        disposable1.dispose()
    }
}